package j43;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chengshuai
 * @date 2021/4/16 23:46
 */
public class ShareResource {
    private int number = 1;
    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void f5() {
        lock.lock();
        //1、判断
        try {
            while (number != 1) {
                condition1.await();
            }
            //2、干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3、通知
            number = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void f10() {
        lock.lock();
        //1、判断
        try {
            while (number != 2) {
                condition2.await();
            }
            //2、干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3、通知
            number = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void f15() {
        lock.lock();
        //1、判断
        try {
            while (number != 3) {
                condition3.await();
            }
            //2、干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            //3、通知
            number = 3;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        ShareResource resource = new ShareResource();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                resource.f5();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                resource.f10();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                resource.f15();
            }
        },"C").start();
    }
}
